<template>
  <div>
    <h2>当前的和为: {{ sum }}</h2>
    <button @click="sum++">点我+1</button>
    <hr />
    <h2>当前的信息为: {{ msg }}</h2>
    <button @click="msg += '!'">修改当前信息</button>
    <hr />
    <h2>姓名: {{ person.name }}</h2>
    <h2>年龄: {{ person.age }}</h2>
    <h2>薪资: {{ person.job.j1.salary }}K</h2>
    <button @click="person.name += '!'">修改姓名</button>
    <button @click="person.age++">修改年龄</button>
    <button @click="person.job.j1.salary++">涨薪</button>
  </div>
</template>

<script>
import { ref, reactive, watch } from "vue";
export default {
  name: "Demo",

  setup() {
    let sum = ref(0);
    let msg = ref("你好呀");
    let person = reactive({
      name: "张三",
      age: 25,
      job: {
        j1: {
          salary: 6,
        },
      },
    });

    //情况1, 监视ref定义的单个响应式数据
    watch(sum, (newValue, oldValue) => {
      console.log("sum改变了", newValue, oldValue);
    });

    //情况2， 监听ref定义的多个响应式数据
    watch([sum, msg], (newValue, oldValue) => {
      console.log("sum或者msg改变了", newValue, oldValue);
    });

    /**
     * 情况3， 监听reactive定义的全部响应式数据
     *    注意1： watch监听reactive定义的数据，oldValue无法被正确获取
     *    注意2： watch监听reactive定义的数据，deep设置无效
     **/

    watch(person,(newValue, oldValue) => {
        console.log("person改变了", newValue, oldValue)
      }, {immediate: true, deep:false});  //deep设置无效，强制开启
    
    //情况4  监听reactive中的单个响应式数据, oldValue也能被正确获取
    watch(()=>person.age, (newValue, oldValue) => {
      console.log("person的age改变了!", newValue, oldValue);
    })

    //情况五 监听reactive中的某些响应式数据, oldValue也能被正确获取
    watch([()=>person.age, ()=>person.job.j1.salary], (newValue, oldValue) => {
      console.log("person的age或者salary改变了!", newValue, oldValue);
    })

    //特殊情况 监听reactive中的定义的对象的时候，需要deep才能深度监视，deep设置有效
    watch(()=>person.job,  (newValue, oldValue) => {
      console.log("person的salary改变了!", newValue, oldValue);
    }, {deep:true}) //此处由于监视的是reactive素定义的对象中的某个属性，所以deep配置有效

    return {
      sum,
      msg,
      person,
    };
  },
};
</script>